﻿using CloudApiServer.Services;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using static log4net.Appender.RollingFileAppender;
using System.Web.UI.WebControls;
using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData;

namespace CloudApiServer.Controllers
{
    /// <summary>
    /// 浙江医保
    /// </summary>
    [RoutePrefix("fsi/api")]
    public class FsiApiZheJiangController : ApiController
    {
        private readonly SignInSignOutService _signInSignOuService;
        private readonly FsiPsnInfoService _fsiPsnInfoService;
        private readonly FsiDrugStoreService _fsiDrugStoreService;
        private readonly CatalogQueryService _catalogQueryService;
        private readonly FsiIntegratedQueryService _fsiIntegratedQueryService;
        private readonly YbSettlementStmtService _ybSettlementStmtService;
        private readonly RiskConService _riskConService;
        private readonly FileuploadService _fileuploadService;
        private readonly GoodsService _goodsService;
        private readonly OutpatientDocInfoService _outpatientDocInfoService;
        private readonly FsiReverseService _fsiReverseService;

        public FsiApiZheJiangController()
        {
            _signInSignOuService = new SignInSignOutService();
            _fsiPsnInfoService = new FsiPsnInfoService();
            _fsiDrugStoreService = new FsiDrugStoreService();
            _catalogQueryService = new CatalogQueryService();
            _fsiIntegratedQueryService = new FsiIntegratedQueryService();
            _ybSettlementStmtService = new YbSettlementStmtService();
            _riskConService = new RiskConService();
            _fileuploadService = new FileuploadService();
            _goodsService = new GoodsService();
            _outpatientDocInfoService = new OutpatientDocInfoService();
            _fsiReverseService = new FsiReverseService();
        }

        /// <summary>
        /// 医保接口没找到的统一接口返回
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        public IHttpActionResult FsiNotFound(HttpRequestMessage request)
        {
            string url = request.RequestUri.ToString();
            string Method = request.Method.ToString();
            string Errnum = LogHelper.GetErrornumber();
            try
            {
                if (string.IsNullOrEmpty(request.Content.ReadAsStringAsync().Result))
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参为空！当前请求入参：" +
                                  request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    var fsiRequest =
                        JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(request.Content.ReadAsStringAsync()
                            .Result);
                    string infno = fsiRequest.infno;
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加！当前请求的接口号：{infno},当前请求入参：" +
                                  request.Content.ReadAsStringAsync().Result
                    };
                    return Json(FsiHeader);
                }
            }
            catch (JsonReaderException)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg =
                        $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且入参格式不正确！服务端无法正常反序列化！请检查入参是否为Json格式！当前请求入参：" +
                        request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg =
                        $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请求的接口【{url}】方法【{Method}】暂未添加且服务端程序处理异常！请联系管理员排查！当前异常提示：{ex.Message},当前请求入参：" +
                        request.Content.ReadAsStringAsync().Result
                };
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 9001签到
        /// </summary>
        /// <returns></returns>
        [Route("signInSignOutService/signIn")]
        [HttpPost]
        public async Task<IHttpActionResult> signIn(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputSignIn>>(
                        await request.Content.ReadAsStringAsync());
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var signin = await _signInSignOuService.SignInAsync(fsiRequest, this.GetType().Name);
                var response = new FsiHeader<outputsignInOut>
                {
                    output = signin,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(response);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 9002签退
        /// </summary>
        /// <returns></returns>
        [Route("signInSignOutService/signOut")]
        [HttpPost]
        public async Task<IHttpActionResult> signOut(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputSignOut>>(request.Content.ReadAsStringAsync()
                        .Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var siginout = await _signInSignOuService.SignOutAsync(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    output = siginout,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 1101 人员信息获取
        /// </summary>
        /// <returns></returns>
        [Route("fsiPsnInfoService/queryPsnInfo")]
        [HttpPost]
        public async Task<IHttpActionResult> queryPsnInfo(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryPsnInfoRequest>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                var queryPsnInfo = await _fsiPsnInfoService.QueryPsnInfo(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputQueryPsnInfo>
                {
                    output = queryPsnInfo,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 2101/2101A 药店预结算接口
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsPreA")]
        [Route("fsiDrugStoreService/drugstoreSettleAccountsPre")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsPreA(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var drugstoreSettleAccountsPreA =
                    await _fsiDrugStoreService.DrugstoreSettleAccountsPre(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                {
                    output = drugstoreSettleAccountsPreA,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 2102/2102A 药店结算接口
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsA")]
        [Route("fsiDrugStoreService/drugstoreSettleAccounts")]
        [Route("fsiDrugStoreService/drugstoreSettleAccountsV2")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsA(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.statesignon == true)
                {
                    if (string.IsNullOrEmpty(fsiRequest.sign_no))
                    {
                        throw new Exception("校验签到信息失败：传入的签到号为空！");
                    }

                    bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);

                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var drugstoreSettleAccountsA =
                    await _fsiDrugStoreService.DrugstoreSettleAccounts(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                {
                    output = drugstoreSettleAccountsA,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 2103退款接口
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleRevoke")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleRevoke(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleRevokeRequest>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var drugstoreSettleRevoke =
                    await _fsiDrugStoreService.DrugstoreSettleRevoke(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputDrugstoreSettleRevoke>
                {
                    output = drugstoreSettleRevoke,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 2601冲正交易
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("reverseService/revsMethod")]
        [HttpPost]
        public async Task<IHttpActionResult> revsMethod(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputRevsMethod>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                bool flag = await _fsiReverseService.RevsMethod(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        output = null,
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg =
                            $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用冲正服务FsiReverseService.RevsMethod返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }
        
        /// <summary>
        /// 3301上传对照
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("catalogCompService/catalogCompUp")]
        [HttpPost]
        public async Task<IHttpActionResult> catalogCompUp(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputCatalogCompUp>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                bool flag = await _catalogQueryService.CatalogCompUp(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        output = null,
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg =
                            $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用目录上传服务CatalogQueryService.CatalogCompUp返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3302上传撤销
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("catalogCompService/deleteCatalogCompAudited")]
        [HttpPost]
        public async Task<IHttpActionResult> deleteCatalogCompAudited(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputDeleteCatalogCompAudited>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                bool flag = await _catalogQueryService.DeleteCatalogCompAudited(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    FsiHeader<outputsignInOut> FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        output = null,
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg =
                            $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用目录上传服务CatalogQueryService.DeleteCatalogCompAudited返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 1317上传信息查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("catalogqueryservice/queryMedListMapByPage")]
        [HttpPost]
        public async Task<IHttpActionResult> queryMedListMapByPage(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryMedListMapByPageRequest>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                DateTime dateTime = DateTime.Now;
                Random rnd = new Random();
                var outputQueryMedListMapByPage =
                    await _catalogQueryService.QueryMedListMapByPage(fsiRequest, this.GetType().Name);
                FsiHeader<OutputQueryMedListMapByPage> FsiHeader = new FsiHeader<OutputQueryMedListMapByPage>
                {
                    output = outputQueryMedListMapByPage,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3201对账汇总
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("ybSettlementStmtService/stmtTotal")]
        [HttpPost]
        public async Task<IHttpActionResult> stmtTotal(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputStmtTotalRequest>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var stmtinfo = await _ybSettlementStmtService.StmtTotal(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputStmtTotal>
                {
                    output = stmtinfo,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }


        /// <summary>
        /// 3202对账明细 
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("ybSettlementStmtService/stmtDetail")]
        [HttpPost]
        public async Task<IHttpActionResult> stmtDetail(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputStmtDetailRequest>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var fileinfo = await _ybSettlementStmtService.StmtDetail(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputStmtDetail>
                {
                    output = fileinfo,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 5301人员慢特病查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("fsiIntegratedQueryService/queryPsnOpspReg")]
        [HttpPost]
        public async Task<IHttpActionResult> queryPsnOpspReg(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryPsnOpspReg>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var outputQueryPsnOpspReg =
                    await _fsiIntegratedQueryService.QueryPsnOpspReg(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputQueryPsnOpspReg>
                {
                    output = outputQueryPsnOpspReg,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 5206年度费用累计
        /// </summary>
        /// <returns></returns>
        [Route("fsiIntegratedQueryService/queryFixmedinsPracPsnSum")]
        [HttpPost]
        public async Task<IHttpActionResult> queryFixmedinsPracPsnSum(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputQueryFixmedinsPracPsnSum>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                string psn_no = fsiRequest.Input.data.psn_no;
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var outputCuminfo =
                    await _fsiIntegratedQueryService.QueryFixmedinsPracPsnSum(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<outputCuminfo>
                {
                    output = outputCuminfo,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }


        /// <summary>
        /// 3101明细审核事前分析
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("riskConService/beforeAnalyze")]
        [HttpPost]
        public async Task<IHttpActionResult> beforeAnalyze(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputRiskConServiceresult>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var outputriskConService = await _riskConService.BeforeAnalyze(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputriskConService>
                {
                    output = outputriskConService,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3102明细审核事中分析
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("riskConService/courseAnalyze")]
        [HttpPost]
        public async Task<IHttpActionResult> courseAnalyze(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputRiskConServiceresult>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var outputriskConService = await _riskConService.CourseAnalyze(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputriskConService>
                {
                    output = outputriskConService,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3501 盘存上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsUpload")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsUpload(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsUpload>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var flag = await _goodsService.GoodsUpload(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsUpload返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }


        /// <summary>
        /// 3502 库存变更
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsUpdate")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsUpdate(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsUpdate>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                DateTime dateTime = DateTime.Now;
                Random rnd = new Random();
                var flag = await _goodsService.GoodsUpdate(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsUpdate返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3503 采购上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsBuy")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsBuy(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsBuy>>(request.Content.ReadAsStringAsync()
                        .Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var flag = await _goodsService.GoodsBuy(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsBuy返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }


        /// <summary>
        /// 3504 采购退货上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsBuyReturn")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsBuyReturn(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsBuy>>(request.Content.ReadAsStringAsync()
                        .Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var flag = await _goodsService.GoodsBuyReturn(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsBuyReturn返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3505 销售上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsSell")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsSell(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsSell>>(request.Content.ReadAsStringAsync()
                        .Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var flag = await _goodsService.GoodsSell(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsSell返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3506 销售退货
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsSellReturn")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsSellReturn(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsSell>>(request.Content.ReadAsStringAsync()
                        .Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var flag = await _goodsService.GoodsSellReturn(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsSellReturn返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 3507 上传记录删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("goodsService/goodsInfoDelete")]
        [HttpPost]
        public async Task<IHttpActionResult> goodsInfoDelete(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputGoodsInfoDelete>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var flag = await _goodsService.GoodsInfoDelete(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用进销存上传服务GoodsService.GoodsInfoDelete返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /*浙江省电子处方流转平台OPSP接口*/
        /// <summary>
        /// 7202接口
        /// </summary>
        /// <returns></returns>
        [Route("opsp/7202")]
        [HttpPost]
        public async Task<IHttpActionResult> opsp7202(HttpRequestMessage request)
        {
            //throw new Exception("当前入参：" + request.Content.ReadAsStringAsync().Result);
            DataTable dt = new DataTable();
            string connectionString =
                $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    var fsiRequest =
                        JsonConvert.DeserializeObject<FsiRequestHeader<InputOpsp7202Request>>(request.Content
                            .ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string psn_name = fsiRequest.Input.data.psn_name;
                    if (string.IsNullOrEmpty(psn_no))
                    {
                        throw new Exception("参数校验失败：传入的人员编号为空，请检查入参！当前入参：" +
                                            request.Content.ReadAsStringAsync().Result);
                    }

                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }

                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter,
                            fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_prescription where psn_no=@psn_no";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count != 0)
                            {
                                List<DataOpsp7202> dataList = new List<DataOpsp7202>();
                                foreach (DataRow row in dt.Rows)
                                {
                                    DataOpsp7202 item = new DataOpsp7202
                                    {
                                        auth_rxno = row["auth_rxno"].ToString(),
                                        epc_token = row["epc_token"].ToString(),
                                        expires_in = row["expires_in"].ToString(),
                                        fixmedins_code = row["fixmedins_code"].ToString(),
                                        fixmedins_name = row["fixmedins_name"].ToString(),
                                        prsc_time = row["prsc_time"].ToString(),
                                        dise_codg = row["dise_codg"].ToString(),
                                        dise_name = row["dise_name"].ToString(),
                                        valid_end_time = row["valid_end_time"].ToString()
                                    };
                                    dataList.Add(item);
                                }

                                Random rnd = new Random();
                                DateTime dateTime = DateTime.Now;
                                FsiHeader<outputDataOpsp7202> FsiHeader = new FsiHeader<outputDataOpsp7202>
                                {
                                    output = new outputDataOpsp7202
                                    {
                                        data = dataList
                                    },
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid =
                                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception(
                                    $"查询处方列表失败！人员姓名：{psn_name} 人员编号：{psn_no} 未查询到7202处方列表，如需测试请联系管理员增加相关数据！");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 7203接口
        /// </summary>
        /// <returns></returns>
        [Route("opsp/7203")]
        [HttpPost]
        public async Task<IHttpActionResult> opsp7203(HttpRequestMessage request)
        {
            DataTable dtinfo = new DataTable();
            DataTable dtdetail = new DataTable();
            string connectionString =
                $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    var fsiRequest =
                        JsonConvert.DeserializeObject<FsiRequestHeader<InputOpsp7203Request>>(request.Content
                            .ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string psn_no = fsiRequest.Input.data.psn_no;
                    string epc_token = fsiRequest.Input.data.epc_token ?? fsiRequest.Input.data.epctoken;
                    string auth_rxno = fsiRequest.Input.data.auth_rxno;


                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(epc_token) ||
                        string.IsNullOrEmpty(auth_rxno))
                    {
                        throw new Exception("参数校验失败：传入的人员编号|电子处方令牌|医保处方授权编号为空，请检查入参！当前入参：" +
                                            request.Content.ReadAsStringAsync().Result);
                    }

                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }

                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter,
                            fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }

                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText =
                            "select * from fsi_prescription where psn_no=@psn_no and epc_token=@epc_token and auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        cmd.Parameters.AddWithValue("@epc_token", epc_token);
                        cmd.Parameters.AddWithValue("@auth_rxno", auth_rxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dtinfo.Load(reader);
                            if (dtinfo.Rows.Count == 0)
                            {
                                throw new Exception(
                                    $"查询处方列表失败！人员编号：{psn_no}处方授权编号：{auth_rxno} 未查询到处方列表，如需测试请联系管理员增加相关数据！");
                            }

                            cmd.Parameters.Clear();
                        }

                        cmd.CommandText =
                            "select * from fsi_prescription_detail where psn_no=@psn_no and auth_rxno=@auth_rxno";
                        cmd.Parameters.AddWithValue("@psn_no", psn_no);
                        cmd.Parameters.AddWithValue("@epc_token", epc_token);
                        cmd.Parameters.AddWithValue("@auth_rxno", auth_rxno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            List<RxDetlList> dataList = new List<RxDetlList>();
                            dtdetail.Load(reader);
                            if (dtdetail.Rows.Count != 0)
                            {
                                foreach (DataRow row in dtdetail.Rows)
                                {
                                    RxDetlList item = new RxDetlList
                                    {
                                        med_list_codg = row["med_list_codg"].ToString(),
                                        fixmedins_hilist_id = row["fixmedins_hilist_id"].ToString(),
                                        hosp_prep_flag = row["hosp_prep_flag"].ToString(),
                                        rx_item_type_code = row["rx_item_type_code"].ToString(),
                                        rx_item_type_name = row["rx_item_type_name"].ToString(),
                                        tcmdrug_type_code = row["tcmdrug_type_code"].ToString(),
                                        tcmdrug_type_name = row["tcmdrug_type_name"].ToString(),
                                        tcmherb_foote = row["tcmherb_foote"].ToString(),
                                        medn_type_code = row["medn_type_code"].ToString(),
                                        medn_type_name = row["medn_type_name"].ToString(),
                                        main_medc_flag = row["main_medc_flag"].ToString(),
                                        urgt_flag = row["urgt_flag"].ToString(),
                                        bas_medn_flag = row["bas_medn_flag"].ToString(),
                                        imp_drug_flag = row["imp_drug_flag"].ToString(),
                                        drug_prodname = row["drug_prodname"].ToString(),
                                        drug_genname = row["drug_genname"].ToString(),
                                        drug_dosform = row["drug_dosform"].ToString(),
                                        drug_spec = row["drug_spec"].ToString(),
                                        prdr_name = row["prdr_name"].ToString(),
                                        drug_cnt = Convert.ToDecimal(row["drug_cnt"]),
                                        medc_way_codg = row["medc_way_codg"].ToString(),
                                        medc_way_dscr = row["medc_way_dscr"].ToString(),
                                        medc_endtime = row["medc_endtime"].ToString(),
                                        medc_begntime = row["medc_begntime"].ToString(),
                                        medc_days = Convert.ToDecimal(row["medc_days"]),
                                        drug_dosunt = row["drug_dosunt"].ToString(),
                                        sin_doscnt = Convert.ToDecimal(row["sin_doscnt"]),
                                        sin_dosunt = row["sin_dosunt"].ToString(),
                                        used_frqu_codg = row["used_frqu_codg"].ToString(),
                                        used_frqu_name = row["used_frqu_name"].ToString(),
                                        drug_totlcnt = row["drug_totlcnt"].ToString(),
                                        drug_totlnt_emp = row["drug_totlnt_emp"].ToString(),
                                        own_expense_flag = row["own_expense_flag"].ToString(),
                                        hi_nego_drug_flag = row["hi_nego_drug_flag"].ToString(),
                                        refer_d_channel_flag = row["refer_d_channel_flag"].ToString(),
                                        bidding_drug_flag = row["bidding_drug_flag"].ToString(),
                                        hosp_appr_flag = row["hosp_appr_flag"].ToString()
                                    };
                                    dataList.Add(item);
                                }
                            }
                            else
                            {
                                throw new Exception($"查询处方明细列表失败！人员编号：{psn_no} 未查询到7203处方药品列表，如需测试请联系管理员增加相关数据！");
                            }

                            cmd.Parameters.Clear();
                            Random rnd = new Random();
                            DateTime dateTime = DateTime.Now;
                            long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                            var FsiHeader = new FsiHeader<outputDataOpsp7203>
                            {
                                output = new outputDataOpsp7203
                                {
                                    data = new DataOpsp7203
                                    {
                                        hi_rxno = dtinfo.Rows[0]["hi_rxno"].ToString(),
                                        fixmedins_code = dtinfo.Rows[0]["fixmedins_code"].ToString(),
                                        fixmedins_name = dtinfo.Rows[0]["fixmedins_name"].ToString(),
                                        prsc_time = dtinfo.Rows[0]["prsc_time"].ToString(),
                                        rx_file = dtinfo.Rows[0]["rx_file"].ToString(),
                                        rx_trace_code = dtinfo.Rows[0]["rx_trace_code"].ToString(),
                                        prsc_dept_name = dtinfo.Rows[0]["prsc_dept_name"].ToString(),
                                        rx_type_code = dtinfo.Rows[0]["rx_type_code"].ToString(),
                                        rx_type_name = dtinfo.Rows[0]["rx_type_name"].ToString(),
                                        long_rx_flag = dtinfo.Rows[0]["long_rx_flag"].ToString(),
                                        file_suffix = dtinfo.Rows[0]["file_suffix"].ToString()
                                    },
                                    rxDetlList = dataList,
                                    rxOtpinfo = new RxOtpinfo
                                    {
                                        med_type = dtinfo.Rows[0]["med_type"].ToString(),
                                        patn_name = dtinfo.Rows[0]["patn_name"].ToString(),
                                        //patn_age = Convert.ToDecimal(dtinfo.Rows[0]["patn_age"]),
                                        patn_hgt = dtinfo.Rows[0]["patn_hgt"].ToString(),
                                        //patn_wt = Convert.ToDecimal(dtinfo.Rows[0]["patn_wt"]),
                                        gend = dtinfo.Rows[0]["gend"].ToString(),
                                        //geso_val = Convert.ToDecimal(dtinfo.Rows[0]["geso_val"]),
                                        nwb_flag = dtinfo.Rows[0]["nwb_flag"].ToString(),
                                        nwb_age = dtinfo.Rows[0]["nwb_age"].ToString(),
                                        //suck_prd_flag = (int)dtinfo.Rows[0]["suck_prd_flag"],
                                        algs_his = dtinfo.Rows[0]["algs_his"].ToString(),
                                        dise_codg = dtinfo.Rows[0]["dise_codg"].ToString(),
                                        dise_name = dtinfo.Rows[0]["dise_name"].ToString(),
                                        otp_ipt_flag = dtinfo.Rows[0]["otp_ipt_flag"].ToString(),
                                        main_diag_code = dtinfo.Rows[0]["main_diag_code"].ToString(),
                                        main_diag_name = dtinfo.Rows[0]["main_diag_name"].ToString(),
                                        dise_cond_dscr = dtinfo.Rows[0]["dise_cond_dscr"].ToString()
                                    }
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid =
                                    $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 7204处方审核
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("opsp/7204")]
        [HttpPost]
        public IHttpActionResult opsp7204()
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                Guid uuid = Guid.NewGuid();
                var FsiHeader = new FsiHeader<OutputOpsp7204>
                {
                    output = new OutputOpsp7204
                    {
                        data = new DataOutputOpsp7204
                        {
                            flag = "true",
                            rx_chk_biz_sn = uuid.ToString(),
                            rx_info_verify_result = null
                        }
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 7211处方销售出库
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("opsp/7211")]
        [HttpPost]
        public IHttpActionResult opsp7211()
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                var FsiHeader = new FsiHeader<OutputOpsp7204>
                {
                    output = new OutputOpsp7204
                    {
                        data = new DataOutputOpsp7204
                        {
                            flag = "true"
                        }
                    },
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"330000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 7000处方药品明细查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("opsp/7000")]
        [HttpPost]
        public async Task<IHttpActionResult> opsp7000(HttpRequestMessage request)
        {
            DataTable dt = new DataTable();
            string connectionString =
                $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    var fsiRequest =
                        JsonConvert.DeserializeObject<FsiRequestHeader<InuptOpsp7000>>(request.Content
                            .ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    string med_list_codg = fsiRequest.Input.data.med_list_codg;
                    int page_num = fsiRequest.Input.data.page_num;
                    int page_size = fsiRequest.Input.data.page_size;
                    if (string.IsNullOrEmpty(med_list_codg))
                    {
                        throw new Exception("参数校验失败：传入的医保国家编码为空，请检查入参！当前入参：" +
                                            request.Content.ReadAsStringAsync().Result);
                    }

                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }

                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter,
                            fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }

                    int nowpage = page_size * (page_num - 1);
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        //西药中成药
                        if (med_list_codg.StartsWith("X"))
                        {
                            cmd.CommandText =
                                "select med_list_codg,NAT_DRUG_NO,'' as genname, DRUG_PRODNAME as  prodname, reg_name,'101' as list_type, '西药中成药' as list_type_name,DRUG_SPEC as spec_name, PRODENTP_NAME as  prdr_name ,  aprvno, DRUG_DOSFORM as dosform_name,min_pacunt,min_pac_cnt,min_prepunt,'' as poolarea_no,'' as poolarea_name,'0' as dualchnl_flag,'' as begntime,'' as endtime  from ml_xyzcyml where med_list_codg = @med_list_codg limit @nowpage,@page_size";
                        }
                        else if (med_list_codg.StartsWith("Z"))
                        {
                            cmd.CommandText =
                                "select med_list_codg,NAT_DRUG_NO,'' as genname, DRUG_PRODNAME as  prodname, reg_name,'101' as list_type, '西药中成药' as list_type_name,DRUG_SPEC as spec_name, PRODENTP_NAME as  prdr_name ,  aprvno, DRUG_DOSFORM as dosform_name,min_pacunt,min_pac_cnt,min_prepunt,'' as poolarea_no,'' as poolarea_name,'0' as dualchnl_flag,'' as begntime,'' as endtime  from ml_xyzcyml where med_list_codg = @med_list_codg limit @nowpage,@page_size";
                        }
                        //中药饮片
                        else if (med_list_codg.StartsWith("T"))
                        {
                            cmd.CommandText =
                                "select med_list_codg,'' as NAT_DRUG_NO,'' as genname, '' as  prodname, tcmherb_name as  reg_name,'102' as list_type, '中药饮片' as list_type_name, cnvl_used as spec_name, '' as  prdr_name , '' as  aprvno, ''  as dosform_name, '' as min_pacunt,'' as min_pac_cnt, ''as min_prepunt,'' as poolarea_no,'' as poolarea_name,'0' as dualchnl_flag,'' as begntime,'' as endtime  from ml_zyypml where med_list_codg = @med_list_codg limit @nowpage,@page_size";
                        }
                        else
                        {
                            throw new Exception($"校验国家编码属性失败：{med_list_codg}非法或不满足预设的条件!请检查国家编码是否正确或联系管理员!");
                        }

                        cmd.Parameters.AddWithValue("@med_list_codg", med_list_codg);
                        cmd.Parameters.AddWithValue("@page_size", page_size);
                        cmd.Parameters.AddWithValue("@nowpage", nowpage);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count >= 1)
                            {
                                Random rnd = new Random();
                                DateTime dateTime = DateTime.Now;
                                var FsiHeader = new FsiHeader<OutputOpsp7000>
                                {
                                    output = new OutputOpsp7000
                                    {
                                        data = new DataOutputOpsp7000
                                        {
                                            total = 10,
                                            Size = dt.Rows.Count,
                                        },
                                        list = new List<ListOutputOpsp7000>
                                        {
                                            new ListOutputOpsp7000
                                            {
                                                med_list_codg = dt.Rows[0]["med_list_codg"].ToString(),
                                                nat_drug_no = dt.Rows[0]["nat_drug_no"].ToString(),
                                                genname = dt.Rows[0]["genname"].ToString(),
                                                prodname = dt.Rows[0]["prodname"].ToString(),
                                                reg_name = dt.Rows[0]["reg_name"].ToString(),
                                                list_type = dt.Rows[0]["list_type"].ToString(),
                                                list_type_name = dt.Rows[0]["list_type_name"].ToString(),
                                                spec_name = dt.Rows[0]["spec_name"].ToString(),
                                                prdr_name = dt.Rows[0]["prdr_name"].ToString(),
                                                aprvno = dt.Rows[0]["aprvno"].ToString(),
                                                dosform_name = dt.Rows[0]["dosform_name"].ToString(),
                                                min_pacunt = dt.Rows[0]["min_pacunt"].ToString(),
                                                min_pac_cnt = dt.Rows[0]["min_pac_cnt"].ToString(),
                                                min_prepunt = dt.Rows[0]["min_prepunt"].ToString(),
                                                poolarea_no = dt.Rows[0]["poolarea_no"].ToString(),
                                                poolarea_name = dt.Rows[0]["poolarea_name"].ToString(),
                                                dualchnl_flag = dt.Rows[0]["dualchnl_flag"].ToString(),
                                                begntime = dt.Rows[0]["begntime"].ToString(),
                                                endtime = dt.Rows[0]["endtime"].ToString(),
                                            }
                                        },
                                    },
                                    infcode = 0,
                                    warn_msg = null,
                                    cainfo = null,
                                    err_msg = "success",
                                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    signtype = null,
                                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                    inf_refmsgid =
                                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception($"查询目录数据表失败！查询到的医保目录数据总数为：{dt.Rows.Count}");
                            }
                        }
                    }
                    //}
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 9101文件上传
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("fileupload/upload")]
        [HttpPost]
        public async Task<IHttpActionResult> upload(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputFileupload>>(request.Content.ReadAsStringAsync()
                        .Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var outputFileUpload = await _fileuploadService.Upload(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputFileUpload>
                {
                    output = outputFileUpload,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 9102文件下载
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("fileupload/download")]
        [HttpPost]
        public async Task<IHttpActionResult> download(HttpRequestMessage request)
        {
            try
            {
                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputFileDownload>>(request.Content
                        .ReadAsStringAsync().Result);
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var output = await _fileuploadService.Download(fsiRequest, this.GetType().Name);
                return ResponseMessage(output);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }


        /*

        ///以下接口并非浙江省接口，因为路由冲突 需要定义在FSI/API路径下 250315 暂时 废止

        /// <summary>
        /// 2101
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsPre")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsPre(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    Console.WriteLine(request.Content.ReadAsStringAsync().Result);
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }
                            string mdtrt_id = rnd.Next(10000000, 90000000).ToString();
                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                if (fsiRequest.Input.druginfo.med_type != "41"&& fsiadmvs=="33")
                                {
                                    cmd.CommandText = "SELECT * FROM fsi_prescription_detail a  left JOIN fsi_prescription b  on a.auth_rxno = b.auth_rxno where b.hi_rxno =@hi_rxno  and a.med_list_codg=@med_list_codg ";
                                    cmd.Parameters.AddWithValue("@hi_rxno", item.rxno);
                                    cmd.Parameters.AddWithValue("@med_list_codg", item.med_list_codg);
                                    using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                                    {
                                        DataTable dt = new DataTable();
                                        dt.Load(reader);
                                        if (dt.Rows.Count < 1)
                                        {
                                            throw new Exception($"处方药品明细校验失败：【{item.med_list_codg}】商品不存于处方【{item.rxno}】中。");
                                        }
                                    }
                                    cmd.Parameters.Clear();
                                }
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }

                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族

                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付

                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,

                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出

                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付

                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail
                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 0);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", "");
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", "");
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"预结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 2102
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccounts")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccounts(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }

                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            //序列化拓展字段
                            Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                            {
                                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2),
                                Q0001 = 0,
                                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2)
                            };
                            string expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                            string mdtrt_id;
                            string setl_id;
                            mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            //Setldetail detail1 = new Setldetail
                            //{
                            //    fund_pay_type = "650102",
                            //    fund_payamt = 11,
                            //    setl_proc_info = null,
                            //    crt_payb_lmt_amt = 0,
                            //    inscp_scp_amt = 0,
                            //    fund_pay_type_name = "罕见病用药"
                            //};
                            //setldetail.Add(detail1);
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        exp_content = expcontentJson,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,
                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        setl_id = setl_id,
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail

                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 1);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@cum_type_code", "S1100");
                                cmd.Parameters.AddWithValue("@year", dateTime.ToString("yyyy"));
                                cmd.Parameters.AddWithValue("@cum", fsiRequest.Input.druginfo.medfee_sumamt);
                                cmd.Parameters.AddWithValue("@cum_ym", dateTime.ToString("yyyyMM"));
                                cmd.Parameters.AddWithValue("@insutype", dtpsninfo.Rows[0]["insutype"]);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }

        /// <summary>
        /// 2102 V2 河北医保
        /// </summary>
        /// <returns></returns>
        [Route("fsiDrugStoreService/drugstoreSettleAccountsV2")]
        [HttpPost]
        public async Task<IHttpActionResult> drugstoreSettleAccountsV2(HttpRequestMessage request)
        {
            string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }
                    var fsiRequest = JsonConvert.DeserializeObject<FsiRequestHeader<InputDrugstoreSettleAccountsPreA>>(request.Content.ReadAsStringAsync().Result);
                    string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                    List<DrugdetailDrugstoreSettleAccountsPreA> list = new List<DrugdetailDrugstoreSettleAccountsPreA>();
                    list = fsiRequest.Input.drugdetail;
                    string psn_no = fsiRequest.Input.druginfo.psn_no;
                    if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(fsiRequest.fixmedins_code) || list.Count == 0)
                    {
                        throw new Exception("参数校验失败：传入的机构代码|人员编号|待结算的商品数组为空，请检查入参！当前入参：" + request.Content.ReadAsStringAsync().Result);
                    }
                    if (FsiDatainfo.statesignon == true)
                    {
                        if (string.IsNullOrEmpty(fsiRequest.sign_no))
                        {
                            throw new Exception("校验签到信息失败：传入的签到号为空！");
                        }
                        bool sign = await PublicMethod.FsisignIn(fsiRequest.fixmedins_code, fsiRequest.opter, fsiRequest.sign_no);

                        if (sign == false)
                        {
                            throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                        }
                    }
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dtpsninfo = new DataTable();
                    long dtunix = PublicMethod.ConvertToUnixTimestampMillis(dateTime);
                    string createTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    await conn.OpenAsync();
                    using (MySqlTransaction transaction = conn.BeginTransaction())
                    {
                        using (MySqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = "select * from fsi_PsnInfo where psn_no=@psn_no";
                            cmd.Parameters.AddWithValue("@psn_no", psn_no);
                            using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                            {
                                dtpsninfo.Load(reader);
                                if (dtpsninfo.Rows.Count != 1)
                                {
                                    throw new Exception($"查询人员信息表失败！查询到的人员信息总数为：{dtpsninfo.Rows.Count}");
                                }
                                cmd.Parameters.Clear();
                            }
                            string clr_type = "11";
                            if (fsiRequest.Input.druginfo.med_type == "41")
                            {
                                clr_type = "41";
                            }
                            else
                            {
                                clr_type = "11";
                            }

                            List<Detlcutinfo> dataList = new List<Detlcutinfo>();
                            foreach (var item in list)
                            {
                                Detlcutinfo detlcutinfo = new Detlcutinfo
                                {
                                    bas_medn_flag = "0",
                                    med_chrgitm_type = "09",
                                    det_item_fee_sumamt = item.det_item_fee_sumamt,
                                    hi_nego_drug_flag = "0",
                                    fulamt_ownpay_amt = 0,
                                    cnt = item.cnt,
                                    pric = item.pric,
                                    feedetl_sn = item.feedetl_sn,
                                    inscp_scp_amt = item.det_item_fee_sumamt,
                                    drt_reim_flag = "0",
                                    overlmt_amt = 0,
                                    pric_uplmt_amt = item.det_item_fee_sumamt,
                                    selfpay_prop = 0,
                                    preselfpay_amt = 0,
                                    chrgitm_lv = "03"
                                };
                                dataList.Add(detlcutinfo);
                            }
                            //序列化拓展字段
                            Setlinfoexpcontent setlinfoexpcontent = new Setlinfoexpcontent
                            {
                                clcYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.clcYearAcctPay, 2),
                                Q0001 = 0,
                                crtYearAcctPay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.crtYearAcctPay, 2)
                            };
                            string expcontentJson = JsonConvert.SerializeObject(setlinfoexpcontent);
                            string mdtrt_id;
                            string setl_id;
                            mdtrt_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            setl_id = $"{fsiadmvs}0000{dtunix}000{rnd.Next(10000000, 90000000).ToString()}";
                            List<Setldetail> setldetail = new List<Setldetail>();
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310200",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险个人账户基金"
                                };
                                setldetail.Add(detail);
                            }
                            if (fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt != 0)
                            {
                                Setldetail detail = new Setldetail
                                {
                                    fund_pay_type = "310100",
                                    fund_payamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),
                                    setl_proc_info = null,
                                    crt_payb_lmt_amt = 0,
                                    inscp_scp_amt = 0,
                                    fund_pay_type_name = "城镇职工基本医疗保险统筹基金"
                                };
                                setldetail.Add(detail);
                            }
                            //Setldetail detail1 = new Setldetail
                            //{
                            //    fund_pay_type = "650102",
                            //    fund_payamt = 11,
                            //    setl_proc_info = null,
                            //    crt_payb_lmt_amt = 0,
                            //    inscp_scp_amt = 0,
                            //    fund_pay_type_name = "罕见病用药"
                            //};
                            //setldetail.Add(detail1);
                            var FsiHeader = new FsiHeader<outputDrugstoreSettleAccountsPreA>
                            {
                                output = new outputDrugstoreSettleAccountsPreA
                                {
                                    detlcutinfo = dataList,
                                    setlinfo = new Setlinfo
                                    {
                                        setl_time = dateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                        cvlserv_pay = FsiDatainfo.cvlserv_pay,//公务员医疗补助资金
                                        hifdm_pay = FsiDatainfo.hifdm_pay,//伤残人员医疗保障基金支出
                                        cvlserv_flag = dtpsninfo.Rows[0]["cvlserv_flag"].ToString(),//公务员标志
                                        med_type = fsiRequest.Input.druginfo.med_type,
                                        exp_content = expcontentJson,
                                        brdy = dtpsninfo.Rows[0]["brdy"].ToString(),
                                        naty = dtpsninfo.Rows[0]["naty"].ToString(),//民族
                                        psn_cash_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.psn_cash_pay, 2),//现金支付
                                        certno = dtpsninfo.Rows[0]["certno"].ToString(),//身份证号码
                                        hifmi_pay = FsiDatainfo.hifmi_pay,//居民大病保险资金支出
                                        psn_no = fsiRequest.Input.druginfo.psn_no,
                                        act_pay_dedc = FsiDatainfo.act_pay_dedc,//实际支付起付线
                                        mdtrt_cert_type = fsiRequest.Input.druginfo.mdtrt_cert_type,

                                        balc = Math.Round(Convert.ToDouble(dtpsninfo.Rows[0]["balc"]) - Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2), 2),
                                        medins_setl_id = $"{fsiRequest.fixmedins_code}{dateTime.ToString("yyyyMMddHHmmssffff")}",
                                        psn_cert_type = dtpsninfo.Rows[0]["psn_cert_type"].ToString(),
                                        acct_mulaid_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_mulaid_pay, 2),//个人账户共济支付金额
                                        clr_way = "1",
                                        hifob_pay = FsiDatainfo.hifob_pay,//职工大额医疗费用补助基金支出
                                        oth_pay = FsiDatainfo.oth_pay,//其他支出
                                        medfee_sumamt = fsiRequest.Input.druginfo.medfee_sumamt,
                                        hifes_pay = FsiDatainfo.hifes_pay,//企业补充医疗保险基金支出
                                        gend = dtpsninfo.Rows[0]["gend"].ToString(),
                                        mdtrt_id = mdtrt_id,
                                        acct_pay = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.acct_pay, 2),//个人账户支出
                                        fund_pay_sumamt = Math.Round(fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, 2),//基金支付
                                        fulamt_ownpay_amt = FsiDatainfo.fulamt_ownpay_amt,//全自费金额
                                        hosp_part_amt = FsiDatainfo.hosp_part_amt,//医院负担金额
                                        setl_id = setl_id,
                                        inscp_scp_amt = FsiDatainfo.inscp_scp_amt,//符合政策范围金额
                                        insutype = fsiRequest.Input.druginfo.insutype,
                                        maf_pay = FsiDatainfo.maf_pay, //医疗救助基金支出
                                        psn_name = dtpsninfo.Rows[0]["psn_name"].ToString(),
                                        psn_part_amt = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //个人负担总额
                                        clr_optins = null,
                                        pool_prop_selfpay = FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支付比例
                                        psn_type = dtpsninfo.Rows[0]["psn_type"].ToString(),
                                        hifp_pay = fsiRequest.Input.druginfo.medfee_sumamt * FsiDatainfo.fund_pay_sumamt, //基本医疗保险统筹基金支出
                                        overlmt_selfpay = FsiDatainfo.overlmt_selfpay, //超限价金额
                                        preselfpay_amt = FsiDatainfo.preselfpay_amt, //先行自付金额
                                        age = PublicMethod.CalculateAge(Convert.ToDateTime(dtpsninfo.Rows[0]["brdy"]), dateTime),
                                        clr_type = clr_type,
                                    },
                                    setldetail = setldetail

                                },
                                infcode = 0,
                                warn_msg = null,
                                cainfo = null,
                                err_msg = "success",
                                refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                signtype = null,
                                respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                                inf_refmsgid = $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                            };
                            string JsonString = JsonConvert.SerializeObject(FsiHeader);
                            cmd.Transaction = transaction;
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_order  VALUES (null, @fixmedins_code,@fixmedins_name,@order_state,@med_type,@psn_no,@setl_id,@mdtrt_id, @SettleAccountspreAInput,@SettleAccountspreAOutput,@SettleAccountsAInput,@SettleAccountsAOutput,@RevokeInput,@RevokeOutput,@create_time,@update_time)";
                                cmd.Parameters.AddWithValue("@fixmedins_code", fsiRequest.fixmedins_code);
                                cmd.Parameters.AddWithValue("@fixmedins_name", fsiRequest.fixmedins_name);
                                cmd.Parameters.AddWithValue("@order_state", 1);
                                cmd.Parameters.AddWithValue("@med_type", fsiRequest.Input.druginfo.med_type);
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@setl_id", setl_id);
                                cmd.Parameters.AddWithValue("@mdtrt_id", mdtrt_id);
                                cmd.Parameters.AddWithValue("@SettleAccountspreAInput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountspreAOutput", "");
                                cmd.Parameters.AddWithValue("@SettleAccountsAInput", request.Content.ReadAsStringAsync().Result);
                                cmd.Parameters.AddWithValue("@SettleAccountsAOutput", JsonString);
                                cmd.Parameters.AddWithValue("@RevokeInput", "");
                                cmd.Parameters.AddWithValue("@RevokeOutput", "");
                                cmd.Parameters.AddWithValue("@create_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                cmd.Parameters.AddWithValue("@update_time", dateTime.ToString("yyyy-MM-dd HH-mm-ss"));
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入订单记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            try
                            {
                                cmd.CommandText = "INSERT INTO fsi_queryfixmedinspracpsnsum  VALUES (@psn_no,@cum_type_code,@year,@cum,@cum_ym,@insutype)";
                                cmd.Parameters.AddWithValue("@psn_no", fsiRequest.Input.druginfo.psn_no);
                                cmd.Parameters.AddWithValue("@cum_type_code", "S1100");
                                cmd.Parameters.AddWithValue("@year", dateTime.ToString("yyyy"));
                                cmd.Parameters.AddWithValue("@cum", fsiRequest.Input.druginfo.medfee_sumamt);
                                cmd.Parameters.AddWithValue("@cum_ym", dateTime.ToString("yyyyMM"));
                                cmd.Parameters.AddWithValue("@insutype", dtpsninfo.Rows[0]["insutype"]);
                                await cmd.ExecuteNonQueryAsync();
                                cmd.Parameters.Clear();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                throw new Exception($"结算处理失败：插入费用累计记录失败！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                            }
                            transaction.Commit();
                            return Json(FsiHeader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                    };
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }
        */
        /// <summary>
        /// 河北医保 电子凭证入参地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("hsecfc/localQrCodeQuery")]
        [HttpPost]
        public async Task<IHttpActionResult> localQrCodeQuery(HttpRequestMessage request)
        {
            string orgid = "";
            string connectionString =
                $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
            using (MySqlConnection conn = new MySqlConnection(connectionString))
            {
                try
                {
                    var fsiRequest =
                        JsonConvert.DeserializeObject<FsiRequestEccCodeHeader<DataEcCodeRequest>>(request.Content
                            .ReadAsStringAsync().Result);
                    orgid = fsiRequest.orgId;
                    if (FsiDatainfo.stateFsiApi == false)
                    {
                        throw new Exception("该接口已被控制台停用！请联系管理员！");
                    }

                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    DataTable dt = new DataTable();
                    await conn.OpenAsync();
                    using (MySqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "select * from fsi_PsnInfo where certno=@certno";
                        cmd.Parameters.AddWithValue("@certno", FsiDatainfo.Ecccodecardno);
                        using (MySqlDataReader reader = (MySqlDataReader)await cmd.ExecuteReaderAsync())
                        {
                            dt.Load(reader);
                            if (dt.Rows.Count == 1)
                            {
                                var FsiHeader = new FsiEcCodeHeader<DataFsiEccCode>
                                {
                                    code = 0,
                                    message = "成功",
                                    orgId = orgid,
                                    data = new DataFsiEccCode
                                    {
                                        chnlId = PublicMethod.GenerateRandomString(32),
                                        ecIndexNo = PublicMethod.GenerateRandomString(32),
                                        ecQrCode = PublicMethod.GenerateRandomString(28),
                                        ecToken = PublicMethod.GenerateRandomString(38),
                                        idNo = FsiDatainfo.Ecccodecardno,
                                        idType = "01",
                                        insuOrg = "",
                                        userName = dt.Rows[0]["psn_name"].ToString(),
                                    }
                                };
                                return Json(FsiHeader);
                            }
                            else
                            {
                                throw new Exception(
                                    $"查询人员信息表失败！根据传入的人员证件号码【{FsiDatainfo.Ecccodecardno}】查询到的人员信息总数为：{dt.Rows.Count}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiEcCodeHeader<DataFsiEccCode>
                    {
                        code = -1,
                        message = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}",
                        orgId = orgid
                    };
                    LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                    return Json(FsiHeader);
                }
                finally
                {
                    if (conn.State == ConnectionState.Open)
                    {
                        await conn.CloseAsync();
                    }
                }
            }
        }


        //以下接口为门诊/医院接口，开发中暂时只支持浙江省

        /// <summary>
        /// 2201门诊挂号
        /// </summary>
        /// <returns></returns>
        [Route("outpatientDocInfoService/outpatientRregistration")]
        [HttpPost]
        public async Task<IHttpActionResult> outpatientRregistration(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputOutpatientRregistration>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                var outputOutpatientRregistration =
                    await _outpatientDocInfoService.OutpatientRregistration(fsiRequest, this.GetType().Name);
                var FsiHeader = new FsiHeader<OutputOutpatientRregistration>
                {
                    output = outputOutpatientRregistration,
                    infcode = 0,
                    warn_msg = null,
                    cainfo = null,
                    err_msg = "success",
                    refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    signtype = null,
                    respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                    inf_refmsgid =
                        $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                };
                return Json(FsiHeader);
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }


        /// <summary>
        /// 2202门诊挂号撤销
        /// </summary>
        /// <returns></returns>
        [Route("outpatientDocInfoService/outpatientRegistrationCancel")]
        [HttpPost]
        public async Task<IHttpActionResult> outpatientRegistrationCancel(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputOutpatientRegistrationCancel>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                bool flag = await _outpatientDocInfoService.OutpatientRegistrationCancel(fsiRequest,
                    this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg =
                            $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用门诊结算服务OutpatientDocInfoService.OutpatientRegistrationCancel返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }

        /// <summary>
        /// 2203A门诊就诊信息上传
        /// </summary>
        /// <returns></returns>
        [Route("outpatientDocInfoService/outpatientMdtrtinfoUpA")]
        [HttpPost]
        public async Task<IHttpActionResult> outpatientMdtrtinfoUpA(HttpRequestMessage request)
        {
            try
            {
                if (FsiDatainfo.stateFsiApi == false)
                {
                    throw new Exception("该接口已被控制台停用！请联系管理员！");
                }

                var fsiRequest =
                    JsonConvert.DeserializeObject<FsiRequestHeader<InputOutpatientMdtrtinfoUpA>>(request.Content
                        .ReadAsStringAsync().Result);
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                if (FsiDatainfo.statesignon == true)
                {
                    bool sign = await _signInSignOuService.SignInStateAsync(fsiRequest.fixmedins_code, fsiRequest.opter,
                        fsiRequest.sign_no);
                    if (sign == false)
                    {
                        throw new Exception("校验签到信息失败：未查询到有效的签到信息！");
                    }
                }

                Random rnd = new Random();
                DateTime dateTime = DateTime.Now;
                bool flag = await _outpatientDocInfoService.OutpatientMdtrtinfoUp(fsiRequest, this.GetType().Name);
                if (flag == true)
                {
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = 0,
                        warn_msg = null,
                        cainfo = null,
                        err_msg = "success",
                        refmsg_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        signtype = null,
                        respond_time = dateTime.ToString("yyyyMMddHHmmssfff"),
                        inf_refmsgid =
                            $"{fsiadmvs}0000{dateTime.ToString("yyyyMMddHHmmssfff")}{rnd.Next(1000000, 10000000).ToString()}"
                    };
                    return Json(FsiHeader);
                }
                else
                {
                    string Errnum = LogHelper.GetErrornumber();
                    var FsiHeader = new FsiHeader<outputsignInOut>
                    {
                        infcode = -1,
                        err_msg =
                            $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！调用门诊结算服务OutpatientDocInfoService.OutpatientMdtrtinfoUpl返回的状态为{flag}！"
                    };
                    return Json(FsiHeader);
                }
            }
            catch (Exception ex)
            {
                string Errnum = LogHelper.GetErrornumber();
                var FsiHeader = new FsiHeader<outputsignInOut>
                {
                    infcode = -1,
                    err_msg = $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}"
                };
                LogHelper.Error( $"[{Errnum}]调用浙江/陕西医保自定义服务失败！请检查！错误内容：{ex.Message} 异常来源：{ex.StackTrace}");
                return Json(FsiHeader);
            }
        }
    }
}